package com.mvc.base.service;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.mvc.base.model.BaseCompany;
import com.mvc.framework.dao.HibernateWebUtils;
import com.mvc.framework.service.BaseService;
import com.mvc.framework.util.FrameworkContextUtils;
import com.mvc.framework.util.PageSearch;

public class BaseCompanyManager<T extends BaseCompany, PK extends Serializable> extends BaseService<T, PK> {

	@Autowired
	protected CompanyManager	companyManager;

	public T get(Serializable id) {
		T t0 = (T) super.get(id);
		if (t0 != null) {
			t0.setCompany(companyManager.getByObjectId(t0.getCompanyId()));
		}
		return t0;
	}

	public void find(final PageSearch page) {
		final Integer userId = FrameworkContextUtils.getCurrentUserId();
		getHibernateTemplate().execute(new HibernateCallback<PageSearch>() {
			public PageSearch doInHibernate(Session session) {
				Criteria criteria = HibernateWebUtils.createCriteria(session, page.getEntityClass(), page.getFilters());
				if (userId != null) {
					criteria.add(Restrictions.sqlRestriction("company_Id in (select B.company_Id from B_USER_COMPANY B"
					        + " where B.user_id = " + userId + ")"));
				}
				if (0 == page.getTotalCount()) {
					criteria.setProjection(Projections.rowCount());
					Object object = criteria.uniqueResult();
					int total = object == null ? 0 : ((Number) object).intValue();
					page.setTotalCount(total);
				}
				addOrder(page, criteria);
				criteria.setProjection(null);
				List items = criteria.setFirstResult(page.getBegin()).setMaxResults(page.getPageSize()).list();
				page.setList(items);
				return page;
			}
		});
	}
}
